// pages/health/health.js
Page({
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      });
    }
  },

  /**
   * 页面的初始数据
   */
  data: {
    // 体重管理数据
    weightData: {
      initial: 52.00,
      current: 52.00,
      target: 60.00,
      gained: 0.50,
      remainingDays: 610,
      initialDate: '2025/09/09',
      targetDate: '2027/05/18'
    },
    selectedUnit: 'kg',
    displayUnitLabel: '公斤',
    weeklyPlanDisplay: '0.09',
    progressPercent: 0,
    displayPercent: 0,
    weightDayCount: 10,
    // 卡路里数据
    calorieData: {
      budget: 1941,
      consumed: 0,
      exercise: 0,
      remaining: 1941
    },
    // 记录状态
    recordStatus: {
      weight: { lastUpdate: '7天前', days: 1 },
      water: { lastUpdate: '7天前' },
      jumpRope: { lastUpdate: '今日未记录' }
    },
    // 功能按钮展开状态
    showFunctions: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.loadUserData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.computeProgress();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadUserData();
  },

  // 从本地存储加载用户数据
  loadUserData() {
    const user = wx.getStorageSync('user') || {};
    
    // 计算已增重
    const currentWeight = parseFloat(user.weight) || 52.0;
    const initialWeight = parseFloat(user.initWeight) || 52.0;
    const gained = currentWeight - initialWeight;
    
    // 更新记录状态
    this.updateRecordStatus();
    
    // 更新体重数据
    this.setData({
      weightData: {
        initial: initialWeight,
        current: currentWeight,
        target: parseFloat(user.targetWeight) || 60.0,
        gained: gained,
        remainingDays: parseFloat(user.remainingDays) || 610,
        initialDate: user.initDate || '2025/09/09',
        targetDate: user.targetDate || '2027/05/18'
      }
    }, () => {
      this.updateDisplayWeights();
      this.computeProgress();
      this.computeWeightDayCount();
    });
  },

  // 更新记录状态
  updateRecordStatus() {
    const records = wx.getStorageSync('weightRecords') || [];
    const today = new Date().toISOString().split('T')[0];
    
    let lastUpdate = '今日未记录';
    let recordCount = records.length;
    
    if (records.length > 0) {
      const lastRecord = records[0];
      const lastDate = new Date(lastRecord.date);
      const todayDate = new Date(today);
      const diffDays = Math.floor((todayDate - lastDate) / (1000 * 60 * 60 * 24));
      
      if (diffDays === 0) {
        lastUpdate = '今天';
      } else if (diffDays === 1) {
        lastUpdate = '昨天';
      } else {
        lastUpdate = `${diffDays}天前`;
      }
    }
    
    this.setData({
      'recordStatus.weight.lastUpdate': lastUpdate,
      'recordStatus.weight.days': recordCount
    });
  },

  // 单位切换
  onUnitTap(e) {
    const unit = e.currentTarget.dataset.unit;
    if (!unit || unit === this.data.selectedUnit) return;
    this.setData({ selectedUnit: unit }, () => {
      this.updateDisplayWeights();
    });
  },

  // 更新展示数值（斤/公斤）
  updateDisplayWeights() {
    const isKg = this.data.selectedUnit === 'kg';
    const factor = isKg ? 1 : 2; // 1公斤=2斤
    const initialDisplay = (this.data.weightData.initial * factor).toFixed(2);
    const currentDisplay = (this.data.weightData.current * factor).toFixed(2);
    const targetDisplay = (this.data.weightData.target * factor).toFixed(2);
    // 确保gained显示正确的符号
    const gainedDisplay = (this.data.weightData.gained * factor).toFixed(2);
    
    // 每周增重计划换算：0.09公斤 = 0.18斤
    const weeklyPlanKg = 0.09;
    const weeklyPlanDisplay = (weeklyPlanKg * factor).toFixed(2);
    
    this.setData({
      'weightData.initialFormatted': initialDisplay,
      'weightData.currentFormatted': currentDisplay,
      'weightData.targetFormatted': targetDisplay,
      'weightData.gainedFormatted': gainedDisplay,
      displayUnitLabel: isKg ? '公斤' : '斤',
      weeklyPlanDisplay: weeklyPlanDisplay
    });
  },

  // 计算线性进度
  computeProgress() {
    const total = Math.abs(this.data.weightData.target - this.data.weightData.initial);
    const progressed = Math.abs(this.data.weightData.gained);
    
    // 处理边界情况
    if (total <= 0) {
      this.setData({
        progressPercent: 0,
        displayPercent: 0
      });
      return;
    }
    
    // 计算百分比，确保在0-100范围内
    const percent = Math.max(0, Math.min(100, (progressed / total) * 100));
    
    this.setData({
      progressPercent: Number(percent.toFixed(1)),
      displayPercent: Number(percent.toFixed(0))
    });
  },

  // 外部更新体重数据时调用，自动刷新进度与展示
  setWeightData(partial) {
    this.setData({ weightData: { ...this.data.weightData, ...partial } }, () => {
      this.updateDisplayWeights();
      this.computeProgress();
      this.computeWeightDayCount();
    });
  },

  // 根据初始日期与当前日期计算“增重第几天”
  computeWeightDayCount() {
    try {
      const startStr = this.data.weightData.initialDate; // 形如 2025/09/09
      if (!startStr) return;
      const start = new Date(startStr.replace(/-/g, '/'));
      const today = new Date();
      // 只保留到日，忽略时间
      const startUTC = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
      const todayUTC = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
      const diffDays = Math.floor((todayUTC - startUTC) / (24 * 60 * 60 * 1000)) + 1;
      this.setData({ weightDayCount: diffDays < 1 ? 1 : diffDays });
    } catch (e) {
      // 保底
      this.setData({ weightDayCount: this.data.weightDayCount || 1 });
    }
  },

  // 绘制体重进度环
  drawWeightProgress() {
    const ctx = wx.createCanvasContext('weightCanvas', this);
    const centerX = 150;
    const centerY = 150;
    const radius = 120;
    const lineWidth = 20;
    
    // 清空画布
    ctx.clearRect(0, 0, 300, 300);
    
    // 绘制背景圆环
    ctx.setStrokeStyle('#e8f5e8');
    ctx.setLineWidth(lineWidth);
    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
    ctx.stroke();
    
    // 计算进度（已增重/目标增重）
    const progress = this.data.weightData.gained / (this.data.weightData.target - this.data.weightData.initial);
    const progressAngle = Math.min(progress * 2 * Math.PI, 2 * Math.PI);
    
    // 绘制进度圆环
    ctx.setStrokeStyle('#10b981');
    ctx.setLineWidth(lineWidth);
    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + progressAngle);
    ctx.stroke();
    
    // 绘制中心发光点
    if (progress > 0) {
      const endX = centerX + Math.cos(-Math.PI / 2 + progressAngle) * radius;
      const endY = centerY + Math.sin(-Math.PI / 2 + progressAngle) * radius;
      
      ctx.setFillStyle('#10b981');
      ctx.beginPath();
      ctx.arc(endX, endY, 12, 0, 2 * Math.PI);
      ctx.fill();
      
      // 发光效果
      ctx.setFillStyle('rgba(16, 185, 129, 0.3)');
      ctx.beginPath();
      ctx.arc(endX, endY, 20, 0, 2 * Math.PI);
      ctx.fill();
    }
    
    ctx.draw();
  },

  // 添加体重记录
  onAddWeight() {
    // 获取最近的体重记录作为参考
    const records = wx.getStorageSync('weightRecords') || [];
    const lastWeight = records.length > 0 ? records[0].weight : this.data.weightData.current;
    
    wx.showModal({
      title: '添加体重记录',
      content: '',
      editable: true,
      placeholderText: '请输入体重(kg)',
      success: (res) => {
        if (res.confirm && res.content) {
          const weight = parseFloat(res.content);
          if (!isNaN(weight) && weight > 0 && weight < 300) {
            const gained = weight - this.data.weightData.initial;
            
            // 更新本地存储
            const user = wx.getStorageSync('user') || {};
            user.weight = weight;
            wx.setStorageSync('user', user);
            
            // 保存到体重记录历史
            this.saveWeightRecord(weight);
            
            // 使用setWeightData方法确保所有相关计算都正确更新
            this.setWeightData({
              current: weight,
              gained: gained
            });
            
            // 显示变化信息
            const change = weight - lastWeight;
            const changeText = change > 0 ? `+${change.toFixed(1)}kg` : `${change.toFixed(1)}kg`;
            
            wx.showToast({
              title: `记录成功 ${changeText}`,
              icon: 'success',
              duration: 2000
            });
          } else {
            wx.showToast({
              title: '请输入有效体重(0-300kg)',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 保存体重记录到历史
  saveWeightRecord(weight) {
    const records = wx.getStorageSync('weightRecords') || [];
    const today = new Date().toISOString().split('T')[0];
    
    // 检查今天是否已有记录
    const todayRecord = records.find(r => r.date === today);
    if (todayRecord) {
      // 更新今天的记录
      todayRecord.weight = weight;
      todayRecord.updatedAt = new Date().toISOString();
    } else {
      // 添加新记录
      records.unshift({
        id: Date.now(),
        weight: weight,
        date: today,
        createdAt: new Date().toISOString()
      });
    }
    
    // 限制记录数量，只保留最近30天的记录
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
    const filteredRecords = records.filter(record => {
      const recordDate = new Date(record.date);
      return recordDate >= thirtyDaysAgo;
    });
    
    wx.setStorageSync('weightRecords', filteredRecords);
    
    // 更新记录状态
    this.updateRecordStatus();
  },

  // 智能秤
  onSmartScale() {
    wx.showToast({
      title: '连接智能秤功能',
      icon: 'none'
    });
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
,
  // 跳转到搜索页
  goSearch() {
    wx.navigateTo({ url: '/pages/health/search/search' });
  },
  // 打开AI体重管理师
  openAssistant() {
    wx.navigateTo({ url: '/pages/health/assistant/assistant' });
  },
  // 打开用餐记录页
  openMeal(e) {
    const meal = e.currentTarget.dataset.meal || '早餐';
    wx.navigateTo({ url: `/pages/health/meal/meal?meal=${encodeURIComponent(meal)}` });
  },

  // 显示体重记录历史
  showWeightHistory() {
    const records = wx.getStorageSync('weightRecords') || [];
    
    if (records.length === 0) {
      wx.showToast({
        title: '暂无体重记录',
        icon: 'none'
      });
      return;
    }
    
    // 格式化记录数据
    const formattedRecords = records.slice(0, 10).map(record => {
      const date = new Date(record.date);
      const dateStr = date.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric'
      });
      return `${dateStr}: ${record.weight.toFixed(1)}kg`;
    }).join('\n');
    
    wx.showModal({
      title: `最近${Math.min(records.length, 10)}条记录`,
      content: formattedRecords,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  /**
   * 切换功能按钮显示
   */
  toggleFunctions() {
    this.setData({
      showFunctions: !this.data.showFunctions
    });
  },

  /**
   * 打开AI算热量页面
   */
  openAICalorie(e) {
    const mode = e.currentTarget.dataset.mode;
    
    // 先收起功能按钮
    this.setData({
      showFunctions: false
    });
    
    // 延迟跳转，让收起动画完成
    setTimeout(() => {
      wx.navigateTo({
        url: `/pages/health/ai-calorie/ai-calorie?mode=${mode}`,
        success: () => {
          console.log('跳转到AI算热量页面，模式:', mode);
        },
        fail: (err) => {
          console.error('跳转失败:', err);
          wx.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    }, 300);
  }

})